var base  = require("./base.js");

//webSocket
var ws = {
	link: false,
    functions: [],
	
    start: function (data, event) {
        var that = this;
        if (base.config.socket_url == '') return;
        if (that.link && that.link.readyState == 1) return;
        if (that.link && that.link.readyState != 1) that.link.close();
		
		if(!event) event = false;

        // var data = { cmd: 'reg', userid: that.g.userInfo.userid };
        that.link = uni.connectSocket({
            url: base.config.socket_url,
            header: { 'content-type': 'application/json' },
            method: "POST",
			success: function(res){
			},
			fail: function(res){
			},
            complete: function (res) {
				console.log("Socket connect")
            }
        });
		
		if(event) that.onevent(data);
    },	

    onevent: function (data) {
        var that = this;

        that.link.onError(function (res) {
            console.log('Socket error, restarting...');
            that.link = false;
			setTimeout(function(){				
				that.start(data, true)
			}, 5000)
        });
        that.link.onOpen(function (res) {
            console.log("Socket open");
            that.send(data);
        });
        that.link.onClose(function (res) {
            console.log('Socket close');
            that.link = false;
        });
        that.link.onMessage(function (res) {
			// console.log('recive:', res);
			var arr = JSON.parse(res.data);
			if (typeof arr == 'object') {
				if (arr.cmd == 'reg') {
					console.log("Socket " + arr.cmd + " success.");
				}
				else {
					for (let no in that.functions) {
						that.functions[no](arr)
					}
				}
			}
        });
		that.link.onError(function (res){
			console.log(res)
		});
    },
    close: function () {
        var that = this;
        if (that.link) {
            try {
                that.link.close();
            } catch (e) { }
        }
    },
    send: function (data) {
        var that = this;
        if (that.link && that.link.readyState == 1) {
            that.link.send({ data: JSON.stringify(data) });
        }
    },
    add_func: function (no, func) {
        var that = this;
        if (typeof func == 'function') that.functions[no] = func
    }
}

module.exports = {
	ws: ws,
}